#!/usr/bin/env bash

#**************************************************************************
#*                                                                        *
#*                                 OCaml                                  *
#*                                                                        *
#*                 Stephen Dolan, University of Cambridge                 *
#*                                                                        *
#*   Copyright 2016 Stephen Dolan.                                        *
#*                                                                        *
#*   All rights reserved.  This file is distributed under the terms of    *
#*   the GNU Lesser General Public License version 2.1, with the          *
#*   special exception on linking described in the file LICENSE.          *
#*                                                                        *
#**************************************************************************

set -o pipefail

[ -z "$*" ] && { echo "Usage: $0 libfoo.a" 1>&2; exit 2; }

nm -A -P "$@" | LC_ALL=C awk '
# ignore caml_foo, camlFoo_bar, _caml_foo, _camlFoo_bar
$2 ~ /^(_?caml[_A-Z])/ { next }
# ignore local and undefined symbols
$3 ~ /^[a-zU]$/ { next }
# ignore "main", which should be externally linked
$2 ~ /^_?main$/ { next }
$2 ~ /^_?wmain$/ { next }
# Caml_state escapes the prefixing rule for now
$2 ~ /^_?Caml_state$/ { next }
# for x86 PIC mode
$2 ~ /^__x86.get_pc_thunk./ { next }
# for mingw32
$2 ~ /^.debug_/ { next }
# windows unicode support
$2 ~ /^_win_multi_byte_to_wide_char$/ { next }
$2 ~ /^_win_wide_char_to_multi_byte$/ { next }
# print the rest
{ found=1; print $1 " " $2 " " $3 }
# fail if there were any results
END { exit found ? 1 : 0 }
'
exit $?
